﻿using Heroius.Extension;
using Newtonsoft.Json;
using System;
using System.Drawing;

namespace JsonTest
{
    public class JsonColorConverter : JsonConverter<Color>
    {
        public override Color ReadJson(JsonReader reader, Type objectType, Color existingValue, bool hasExistingValue, JsonSerializer serializer)
        {
            var s = (string)reader.Value;
            s = s.Substring(s.IndexOf('(') + 1);
            var p = s.Remove(s.Length - 1).Split(',');
            return Color.FromArgb((p[3].Trim().As<double>() * 255).As<int>(), p[0].Trim().As<int>(), p[1].Trim().As<int>(), p[2].Trim().As<int>());
        }

        public override void WriteJson(JsonWriter writer, Color value, JsonSerializer serializer)
        {
            writer.WriteValue($"rgba({value.R},{value.G},{value.B},{value.A / 255.0})");
        }
    }
}
